import { computed, defineComponent, inject, PropType } from "vue";
import { CascaderNode, CascaderStore, NodeKeyType } from "./store";
import { CascaderContextKey } from ".";

export interface OptionProps {
    data: CascaderNode[]
    seperator: string
    store: CascaderStore
    filter?: boolean
}

export const Option = defineComponent({
    props: {
        data: {type: Array as PropType<OptionProps['data']>},
        seperator: {type: String as PropType<OptionProps['seperator']>},
        store: {type: Object as PropType<OptionProps['store']>},
        filter: {type: Boolean as PropType<OptionProps['filter']>}
    },
    setup (props: OptionProps) {
        const { store } = props;
        const ctx: any = inject(CascaderContextKey, {});
        const title = computed(() => props.data.map((item: CascaderNode) => item[store.titleField]).join(' / '));
        const onClick = () => {
            const lastItem = props.data[props.data.length - 1];
            if (lastItem.disabled) {
                return;
            }
            const vals: NodeKeyType[] = props.data.map(item => item[store.valueField]);
            if (ctx?.multi) {
                store.checkNode(vals[vals.length - 1], true);
                if (props.filter) {
                    ctx?.clearQuery('');
                }
            } else {
                store.selectedKey.value = vals;
                ctx?.onSelect(props.data[props.data.length - 1]);
            }
        };

        const classList = computed(() => ({
            'cm-cascader-item': true,
            'cm-cascader-item-checked': props.data[props.data.length - 1].checked,
            'cm-cascader-item-disabled': props.data[props.data.length - 1].disabled
        }));
        return () => <div class={classList.value} onClick={onClick}>
            {title.value}
        </div>;
    }
});
